/*jslint sloppy: true */
/*global require, VERSION, module, confirm */
var probe, angular = require('angular');
probe = angular.module("probe", [
	'lemoncase',
	'oc-dialog',
	'ngResource',
	'ui.codemirror',
	'capture',
	'ngFileUpload',
	'ngFileSaver'
]).config(function (ocDialogProvider, $httpProvider) {
	ocDialogProvider.config("ROUTE_PATH", './module/');
	ocDialogProvider.config("BASE_Z_INDEX", 500);

	$httpProvider.defaults.withCredentials = true;
}).run(function ($location, $interval, ocDialog, Project, $rootScope, $window) {
	var bootFn,
		bootArgs = angular.extend({ probe: '', token: ''}, $location.search()),
		protocol = $location.protocol(),
		probe = bootArgs.probe.match(/[0-9a-fA-F]{40}/),
		token = bootArgs.token.match(/[0-9a-f]{16}/),
		bootSetup = $rootScope.bootSetup = {
			mode: 'error', // 'trial', 'full', 'local', 'error', 'runner'
			msg: '',
			isSessionReady: false // for runner mode
		};


	// Define remote service connection.
	function initService(callback) {
		Project.logout(null, function () {
			$rootScope.project = Project.login(null, {
				probeCode: probe[0],
				token: token[0]
			}, function () {
				bootSetup.isSessionReady = true;
				(callback || angular.noop)();
			});
		});
	}

	// Define mode router.
	bootFn = {
		full: function () {
			initService(function () {
				ocDialog.open({name: 'global/master'});
			});
		},
		trial: function () {
			$rootScope.project = new Project();
			ocDialog.open({name: 'global/master'});
		},
		error: function () {
			location.href = 'http://www.lemonce.net/#/docs';
		},
		runner: function () {
			initService();
		}
	};

	// Assert the mode for bootstrap.
	if (protocol !== 'http' && protocol !== 'https') {
		bootSetup.mode = 'error';
	} else if (probe && token) {
		bootSetup.mode = bootArgs.isRunner ? 'runner' : 'full';
	} else {
		bootSetup.mode = 'trial';
	}
	
	// init.
	bootFn[bootSetup.mode]();
	$rootScope.version = { v: VERSION };
	$rootScope.patchUrl = './module/';

	$window.onbeforeunload = function () {
		return confirm();
	};
});

module.exports = probe;
